﻿using System;
using OverStore.Runtime.Storage;
using System.Globalization;

namespace OverStore.Runtime.ObjectRepository.IdentifierProvider
{    
    /// <summary>
    /// Obtains identifier result from <see cref="TypedRecord"/> using user-defined delegate.
    /// </summary>
    /// <typeparam name="TIdentifier">The type of the identifier.</typeparam>
    public class DelegateIdentifierProvider<TIdentifier> : IIdentifierProvider<TIdentifier>
    {
        private readonly Func<TypedRecord, TIdentifier> _ProvideIdentifier;

        /// <summary>
        /// Initializes a new instance of the <see cref="DelegateIdentifierProvider&lt;TIdentifier&gt;"/> class.
        /// </summary>
        /// <param name="provideIdentifier">The provide identifier.</param>
        public DelegateIdentifierProvider(Func<TypedRecord, TIdentifier> provideIdentifier)
        {
            if (Object.ReferenceEquals(provideIdentifier, null))
                throw new ArgumentNullException("provideIdentifier");
            _ProvideIdentifier = provideIdentifier;
        }

        /// <summary>
        /// Gets the identifier from data specified.
        /// </summary>
        /// <param name="data">The data to get identifier from.</param>
        /// <returns>The identifier.</returns>
        /// <exception cref="PersistingRuntimeException">The error occures during gets identifier from set of data.</exception>
        TIdentifier IIdentifierProvider<TIdentifier>.GetIdentifier(TypedRecord data)
        {
            try
            {
                return _ProvideIdentifier(data);
            }
            catch (Exception ex)
            {
                throw new PersistingRuntimeException(
                        "Identifier Provider error: obtaining identifier from data record failed.",
                        ex);
            }
        }
    }
}
